<template>
  <!-- style="width: 500px" -->
  <div>
    <n-card
      class="cardStyle"
      title="登录"
      :bordered="false"
      size="huge"
      role="dialog"
      aria-modal="true"
      @close="store.hideLogin"
    >
      <template #header-extra> </template>

      <n-form
        :model="form"
        :rules="rules"
        label-placement="left"
        label-width="auto"
        ref="formRef"
        @keyup.enter="handleConfirm"
      >
        <div style="margin-bottom: 30px">
          <n-tabs
            type="bar"
            @update:value="upDataValue"
            :default-value="selectValue"
          >
            <template #prefix> 选择登录账号类型 </template>
            <n-tab name="0"> 管理员 </n-tab>
            <n-tab name="1"> 审核员 </n-tab>
            <n-tab name="2"> 填报员 </n-tab>
          </n-tabs>
        </div>

        <n-form-item path="username">
          <n-input
            v-model:value="form.username"
            class="input"
            block
            placeholder="请输入用户名"
          >
            <template #prefix>
              <n-icon :component="PersonOutline" />
            </template>
          </n-input>
        </n-form-item>
        <n-form-item path="password">
          <n-input
            type="password"
            class="input"
            block
            placeholder="请输入密码"
            v-model:value="form.password"
            clearable
          >
            <template #prefix>
              <n-icon :component="LockClosedOutline" />
            </template>
          </n-input>
        </n-form-item>

        <div class="capcha-wrapper">
          <n-form-item path="verifyCode">
            <n-input
              v-model:value="form.verifyCode"
              clearable
              class="input"
              block
              placeholder="请输入验证码"
            >
              <template #prefix>
                <n-icon :component="PrismOutline" />
              </template>
            </n-input>
          </n-form-item>

          <div @click="getSvgverify" class="capcha">
            <div v-html="capchaData"></div>
          </div>
        </div>
      </n-form>

      <n-space> </n-space>
      <template #footer>
        <n-button
          @click="handleConfirm"
          class="login-button"
          type="success"
          strong
          secondary
          style="width: 100%"
          :loading="loginLoading"
          >登录</n-button
        >
        <div class="mention" @click="termsFun">登录即同意《所有条款》</div>
      </template>
    </n-card>

    <n-modal v-model:show="showModal">
      <n-card
        style="width: 600px"
        title="使用条款"
        :bordered="false"
        size="huge"
        role="dialog"
        aria-modal="true"
      >
        <div class="modelStyle">
          <div class="model-title">
            当用户登录时即表示其同意并接受以下条款：
          </div>
          <div
            class="model-content"
            v-for="(item, index) in illustrate"
            :key="index"
          >
            <span style="color: #63e2b7">{{ item.title }}:</span>
            {{ item.content }}
          </div>
        </div>
        <template #footer>
          用户登录即表示其已仔细阅读并同意遵守上述条款，如有违反，用户将承担相应的法律责任。
        </template>
      </n-card>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, watch } from "vue";
import { useMainStore } from "../../store/index";
import { useUserStore } from "@/store/user";
import { useRouter } from "vue-router";
import {
  FlashOutline,
  PersonCircleOutline,
  PersonOutline,
  LockClosedOutline,
  PrismOutline,
} from "@vicons/ionicons5";
import { getVerity, logIN } from "@/api";
import { FormItemRule, useMessage } from "naive-ui";
const formRef = ref();
const message = useMessage();
const store = useMainStore();
const userStore = useUserStore();
const loginLoading = ref(false);
const router = useRouter();
const showModal = ref(false);
const illustrate = ref([
  {
    title: "账户注册与保密性",
    content:
      "用户在注册账户时需提供准确、完整的个人信息，并对其账户信息的保密性负责。用户应妥善保管账户密码，不得将账户信息透露给第三方。",
  },
  {
    title: "使用规则",
    content:
      "用户应遵守平台的使用规则，不得利用平台从事违法、违规或侵犯他人权益的行为，包括但不限于发布违法信息、侵犯他人知识产权等。",
  },
  {
    title: "内容所有权",
    content:
      "内容所有权： 用户在平台上发布的所有内容（包括但不限于文字、图片、音频、视频等）的所有权归用户本人或原作者所有，用户应对其发布的内容负责。",
  },
  {
    title: "隐私保护",
    content:
      "平台将保护用户的个人隐私信息，不会未经用户许可向第三方披露或提供个人信息，除非法律法规另有规定或经用户同意。",
  },
  {
    title: "服务变更与终止",
    content:
      " 平台有权根据业务发展需要对服务内容进行调整或变更，并有权根据用户的违规行为中止或终止用户的账户服务。",
  },
  {
    title: "免责声明",
    content:
      "平台不对用户因使用平台服务而造成的任何直接或间接损失承担责任，包括但不限于利润损失、数据丢失等。",
  },
  {
    title: "法律适用与争议解决",
    content:
      "用户和平台之间的使用协议受中华人民共和国法律管辖，任何因使用平台服务产生的争议应通过友好协商解决，协商不成的可向平台所在地人民法院提起诉讼。",
  },
]);
// 验证码
const getSvgverify = async () => {
  const { data }: any = await getVerity(40, 150, 0);
  console.log(data);
  capchaData.value = data.data;
  form.value.captchaId = data.captchaId;
  form.value.verifyCode = "";
  // getverity.value = data.data
  // loginForm.value.captchaId = data.captchaId
};

const selectValue = ref("0");
const form = ref({
  username: "",
  password: "",
  verifyCode: "",
  captchaId: "",
  selectValue: "0",
});

const upDataValue = (value) => {
  switch (value) {
    case "0":
      form.value.selectValue = "0";
      break;
    case "1":
      form.value.selectValue = "1";
      break;
    case "2":
      form.value.selectValue = "2";
      break;
  }
  console.log("value", form.value.selectValue);
};

const capchaData = ref("");
const rules = {
  username: {
    required: true,
    trigger: ["blur", "input"],
    // message: "请输入用户名",
    validator(rule: FormItemRule, value: string) {
      if (!value) {
        return new Error("请输入用户名");
      } else if (value.indexOf(" ") != -1) {
        return new Error("用户名称里不允许有空格");
      } else if (value.length > 15) {
        return new Error("用户名称字符不能超出15个");
      }
      return true;
    },
  },
  password: {
    required: true,
    trigger: ["blur", "input"],
    validator(rule: FormItemRule, value: string) {
      if (!value) {
        return new Error("请输入密码");
      } else if (value.indexOf(" ") != -1) {
        return new Error("密码里不允许有空格");
      } else if (value.length > 15) {
        return new Error("密码长度不超出15个字符");
      } else if (value.length < 6) {
        return new Error("密码长度不小于6个字符");
      }
      return true;
    },
  },
  verifyCode: {
    required: true,
    trigger: ["blur", "input"],
    validator(rule: FormItemRule, value: string) {
      if (!value) {
        return new Error("请输入验证码");
      } else if (value.indexOf(" ") != -1) {
        return new Error("验证码里不允许有空格");
      } else if (value.length != 4) {
        return new Error("验证码长度应该是4个字符");
      }
      return true;
    },
  },
};
const handleConfirm = async () => {
  const validRes = await formRef.value.validate();
  console.log(validRes);
  loginLoading.value = true;
  console.log(form.value);
  const data = JSON.parse(JSON.stringify(form.value));
  delete data.selectValue;
  logIN(data)
    .then((res: any) => {
      console.log(res);
      if (res.code != 1000) {
        getSvgverify();
        message.error(res.message);
      } else {
        message.success("登录成功");
        localStorage.setItem("token", res.data.token);
        localStorage.setItem("refreshToken", res.data.refreshToken);
        // userStore.updateUserInfo();

        if (store.showLogin) {
          window.location.reload();
        } else {
          router.replace("/");
        }
        store.hideLogin();
        //
      }
    })
    .catch((e) => {
      getSvgverify();
      console.log(e);
      message.error(e);
    })
    .finally(() => {
      loginLoading.value = false;
    });
  // setTimeout(() => {
  //   loginLoading.value = false;
  //   message.success("登录成功");
  //   store.hideLogin();
  // }, 1000);
};
// watch(
//   () => store.showLogin,
//   (val: boolean) => {
//     if (val) {

//     }
//   }
// );

const termsFun = () => {
  showModal.value = true;
};

onMounted(() => {
  getSvgverify();
});
</script>

<style lang="scss" scoped>
.cardStyle {
  width: 500px;
}

.input {
  height: 40px;
  line-height: 40px;
}

.capcha-wrapper {
  display: flex;
}

.capcha {
  width: 180px;
  height: 40px;
  margin-left: 12px;
  cursor: pointer;
  border-radius: 4px;

  svg {
    height: 100%;
    width: 100%;
    position: relative;
  }
}

.login-button {
  width: 80px;
}

.mention {
  margin-top: 12px;
  font-size: 12px;
  cursor: pointer;
  user-select: none;
}

.mention:hover {
  font-weight: bold;
}

.mention:active {
  opacity: 0.8;
}

.modelStyle {
  .model-title {
    font-size: 18px;
    margin-bottom: 10px;
  }

  .model-content {
    font-size: 14px;
    margin-bottom: 5px;
  }
}

@media (max-width: 830px) {
  .cardStyle {
    width: 90vw;
  }

  :deep(.n-card > .n-card__content) {
    padding: 0px;
  }
}

:deep(.n-tabs .n-tabs-nav-scroll-wrapper) {
  display: flex;
  justify-content: right;
}
</style>
